(() => {

    let ele = {};

    ele.peolist = $('#peolist');
    ele.round = $('#round');
    ele.title = $('#title');
    ele.attacker = $('#attacker');

    ele.countdown = $('#conutdown');

    ele.attack_log = $('#attack_log');

    ele.close1 = $('#close1');
    ele.close2 = $('#close2');
    ele.modal_reward = $('#modal-reward');
    ele.endlist = $('#endlist');

    ele.attackimg = $('#attackimg');
	ele.leihead = $('#leihead');
	ele.leipai = $('#leipai');

    ele.listdata = ''

    // 长链接及其参数
	let token = getCookie("token");
	const wsuri = 'ws://rentwx.qunx.cc:2348?token=' + token
    let socket = null
    var timer //设置心跳的定时器


    let ring_id = getUrlParam('id') || 1

    // 攻击者信息
    let attackinfo = {}


    // 准备倒计时
    let ready = {};

    ready.cnum = 5; // 准备时间时长
    ready.timer = null


    window.onpageshow = function (){
        getgameinfo();
        startWebSocket()
    }
    window.onpagehide = function(){
        socket.close()
    }

    ele.close1.onclick = ()=>{
        closeMdl(ele.modal_reward)
        history.back();
        // openMdl
    }
    // ele.close2.onclick = ()=>{
    //     closeMdl(ele.modal_reward)
    //     history.back();
    //     // openMdl
    // }

    // 准备时间倒计时函数
    conutdown()
    function conutdown() {
        clearInterval(ready.timer)
        ready.timer = setInterval(() => {
            ready.cnum--
            ele.countdown.innerHTML = `选择时间：${ready.cnum}秒`
            if (ready.cnum <= 0) {
                clearInterval(ready.timer)
                chooseinfo.cnum = 10;
                choosetime()
            }
        }, 1000);
    }

    let chooseinfo = {}
    chooseinfo.timer = null;
    chooseinfo.cnum = 10;
    // 选择时间倒计时
    function choosetime() {
        clearInterval(chooseinfo.timer)
        chooseinfo.timer = setInterval(() => {
            chooseinfo.cnum--
            ele.countdown.innerHTML = `选择时间：${chooseinfo.cnum}秒`
            if (chooseinfo.cnum <= 0) {
                clearInterval(chooseinfo.timer)
            }
        }, 1000)
    }

    
    // 链接websocket
    function startWebSocket() {
        socket = new WebSocket(wsuri)
        //监听消息接收事件
        socket.addEventListener('message', onMessage)

        //监听WebSocket连接事件
        socket.addEventListener('open', onOpen)

        //监听WebSocket异常事件
        socket.addEventListener('error', onError)

        //监听WebSockt关闭事件
        socket.addEventListener('close', onClose)
    }

    //监听WebSocket连接事件
    function onOpen() {
        // 登录绑定
        // let id = getCookie('userid')
        // let data = {
        //     type: 'login',
        //     data: {
        //         u_id: id
        //     }
        // }
        // socket.send(JSON.stringify(data))
        // 加入房间
        let data2 = {
            type: 'join_room',
            data: {
                ring_id: ring_id
            }
        }
        socket.send(JSON.stringify(data2))
        // 开始心跳
        heart()
    }

    // 设置心跳
    function heart() {
        clearInterval(timer);
        let data = {
            type: "pong",
            data: {}
        }
        timer = setInterval(() => {
            // 传递参数给服务器
            socket.send(JSON.stringify(data))
        }, 30000)
    }


    //监听WebSocket异常事件
    function onError(e) {
        console.error(e)
        // startWebSocket()
    }
    //监听消息接收事件
    function onMessage(e) {
        if (!e) return
        // console.log(e.data)
        let data = JSON.parse(e.data)
        // console.log(data)

        switch (data.type) {
            case 'attack':
                // openTips(data.msg)
                clearInterval(chooseinfo.timer)
                clearInterval(ready.timer)
                notchoose()
                addlog(data.data)
                attackafter(data)
                // getgameinfo()
                if(data.data.next_attacker_uid == 0) {
                    ready.cnum = 10;
                    conutdown()
                }else {
                    chooseinfo.cnum = 10;
                    choosetime()
                }
                break;
            case 'error':
                chooseclear()
                openTips(data.msg)
                break;

            case 'rank': // 开始新的一轮
                clearInterval(chooseinfo.timer)
                clearInterval(ready.timer)
                drawgameinfo(data)
                chooseinfo.cnum = 10;
                choosetime()
                break;
            case 'matchmaking':
                drawend(data.data.list)
				darwTop(data.data.lord)
                clearInterval(chooseinfo.timer)
                clearInterval(ready.timer)
                notchoose()
                ele.countdown.innerHTML = `对局结束`
                // setTimeout(()=>{
                //     history.back()
                // },1500)
                break;
        }
    }

    //监听WebSockt关闭事件
    function onClose(e) {
        // console.log('WebSocket disconnected.', e)
        // startWebSocket()
    }

    // 渲染对局结束列表
    function drawend(data){
        let html = data.map((item,index)=>{
            let headerimg = ''
			let is_fang = '';
            if(item.head_pic == '' || item.head_pic == null) {
                if(item.sex == 1) {
                    headerimg = 'http://img.qxgs.cc/tiantianlaishouzu/img/my/tx1.png'
                }else {
                    headerimg = 'http://img.qxgs.cc/tiantianlaishouzu/img/my/tx2.png'
                }
            }else {
                headerimg = IMG_DOMAIN + item.head_pic
            }
			is_fang = item.is_landlord == 1 ? '<img class="touxian" src="../img/arena/fangdong.png" alt="">' : item.is_landlord == 2 ? '<img class="touxian" src="../img/arena/guanjia.png" alt="">' : '';
            let num = index + 1
            let lv = index == 0?'<img src="http://img.qxgs.cc/tiantianlaishouzu/img/wealth/rank1.png" alt="">':index == 1?'<img src="http://img.qxgs.cc/tiantianlaishouzu/img/wealth/rank2.png" alt="">':index == 2?'<img src="http://img.qxgs.cc/tiantianlaishouzu/img/wealth/rank3.png" alt="">':'<span>'+num+'</span>'
           let baifen1 = item.percentage == 0 ? '' : '<p>（总奖励'+item.percentage+'）</p>'
		   let baifen2 = item.percentage == 0 ? '' : `<p class="rightimg"><span>${item.percentage}%</span></p>`
		   return `<div class="list2">
				  	<div class="leihead leihead2">
				  		<img class="tou" src="${headerimg}" alt="">
				  		${is_fang}
				  	</div>
				  	<p class="name">${item.agent_detail.nick_name}</p>
				  	<p>${item.agent_detail.all_luxury}</p>
				  	<div class="jianbox">
				  		<div class="jianli">
				  			<img src="../img/home/jinbi.png" alt="">
				  			<span>${item.diamond}</span>
				  		</div>
				  		${baifen1}
				  	</div>
				  	${baifen2}
				  </div>`
        }).join('');

        ele.endlist.innerHTML = html
        openMdl(ele.modal_reward)
    }
	
	function darwTop(data) {
		let headerimg = ''
		let is_fang = '';
		if(data.head_pic == '' || data.head_pic == null) {
		    if(data.sex == 1) {
		        headerimg = 'http://img.qxgs.cc/tiantianlaishouzu/img/my/tx1.png'
		    }else {
		        headerimg = 'http://img.qxgs.cc/tiantianlaishouzu/img/my/tx2.png'
		    }
		}else {
		    headerimg = IMG_DOMAIN + data.head_pic
		}
		is_fang = data.is_landlord == 1 ? '<img class="touxian" src="../img/arena/fangdong.png" alt="">' : data.is_landlord == 2 ? '<img class="touxian" src="../img/arena/guanjia.png" alt="">' : '';
		ele.leihead.innerHTML = `<img class="tou" src="${headerimg}" alt="">${is_fang}`
		ele.leipai.innerHTML = data.nick_name
	}
	
    // 首次进入获取游戏信息
    function getgameinfo() {
        let token = getCookie("token");
        ajax({
            url: API_PATH.GET_MATCH,
            method: 'post',
            header: {
                'Authorization': token,
            },
            data: {
                ring_id: ring_id
            },
            success: res => {
                if (res.code == 1) {
                    drawgameinfo(res)
                }
            }
        });
    }

    // 首次进入获取游戏信息渲染
    function drawgameinfo(res) {
        let attackerhtml = ''
        ele.round.innerHTML = `第${res.data.room_detail.round}轮`
        ele.title.innerHTML = `比赛中：第${res.data.room_detail.round}轮`
        ele.listdata = res.data.room_detail.user
        drawpeoinfo(res.data.room_detail.user)
    }

    // 渲染人员数据
    function drawpeoinfo(_data) {
        let attackerhtml = ''
        let myuserid = getCookie('userid')
        // console.log(_data);
        let html = _data.map((item, index) => {
            let prowidth = item.remaining_hp / item.hp * 100 + '%';
            let is_alive = item.is_alive == 1 ? 'listactive' : 'listout'
            let aliveimg = item.is_alive == 1 ? '' : '<img class="outimg" src="http://img.qxgs.cc/tiantianlaishouzu/img/arena/taotai.png" alt="">'
            let is_attacked = item.is_attacked == 1 ? 'is_attacked' : ''
            let headerimg = ''
            if(item.head_pic == '' || item.head_pic == null) {
                if(item.sex == 1) {
                    headerimg = 'http://img.qxgs.cc/tiantianlaishouzu/img/my/tx1.png'
                }else {
                    headerimg = 'http://img.qxgs.cc/tiantianlaishouzu/img/my/tx2.png'
                }
            }else {
                headerimg = IMG_DOMAIN + item.head_pic
            }
            
            let name = item.user_id == myuserid?'我':item.nick_name
            return  `<div class="listcontent ${is_attacked}" data="${item.is_alive}" data2="${item.user_id}">
						<div class="list ${is_alive}">
							<div class="progress progress2">
								<img src="http://img.qxgs.cc/tiantianlaishouzu/img/arena/xuedi.png" alt="">
								<div class="">
									<p></p>
									<span style="width:${prowidth}"></span>
								</div>
							</div>
							<div class="headimg3">
								<img class="headimg4" src="http://img.qxgs.cc/tiantianlaishouzu/img/arena/tx2.png" alt="">
								<img class="headimg5" src="${headerimg}" alt="">
								<div class="listin">
									<span class="caizi">${index + 1}</span>
								</div>
							</div>
							<p class="caizi">${name}</p>
							<span class="hhz">豪华值：${item.luxury}</span>
						</div>
						${aliveimg}
					</div>`;
        }).join('')
        ele.peolist.innerHTML = html
        // 渲染攻击者的数据
        for (let i = 0; i < _data.length; i++) {
            ele.listdata[i].is_attacked = 0 // 首次创建记录是否被攻击
            if (_data[i].is_attacker == 1) {
                // 记录攻击者的数据
                // console.log(111);
                attackinfo.user_id = _data[i].user_id
                attackinfo.is_attacker = _data[i].is_attacker
                if(attackinfo.user_id == myuserid) {
                    ele.attackimg.style.display = 'block'
                }else {
                    ele.attackimg.style.display = 'none'
                }
                // console.log(attackinfo);
                let d = _data[i]
                let prowidth = d.remaining_hp / d.hp * 100 + '%'
                let headerimg2 = ''
                if(_data[i].head_pic == '' || _data[i].head_pic == null) {
                    if(_data[i].sex == 1) {
                        headerimg2 = 'http://img.qxgs.cc/tiantianlaishouzu/img/my/tx1.png'
                    }else {
                        headerimg2 = 'http://img.qxgs.cc/tiantianlaishouzu/img/my/tx2.png'
                    }
                }else {
                    headerimg2 = IMG_DOMAIN + _data[i].head_pic
                }
                attackerhtml += `<div class="progress">
                                        <img src="http://img.qxgs.cc/tiantianlaishouzu/img/arena/xuedi.png" alt="">
                                        <p><span style="width:${prowidth}"></span></p>
                                    </div>
                                    <div class="headimg">
                                        <img class="headimg1" src="http://img.qxgs.cc/tiantianlaishouzu/img/arena/tx.png" alt="">
                                        <img class="headimg2" src="${headerimg2}" alt="">
                                    </div>
                                    <p class="caizi">${d.nick_name}</p>
                                    <span class="hhz">豪华值：${d.luxury}</span>`

                ele.attacker.innerHTML = attackerhtml
                choose();
            }
        }
    }


    // 攻击后修改本地的值
    function attackafter(data) {
        for (let i = 0; i < ele.listdata.length; i++) {
            ele.listdata[i].is_attacker = 0
            if (ele.listdata[i].user_id == data.data.next_attacker_uid) {
                ele.listdata[i].is_attacker = 1
            }
            if (ele.listdata[i].user_id == data.data.attacked_uid) {
                ele.listdata[i].is_attacked = 1
                ele.listdata[i].remaining_hp = data.data.remaining_hp
                if (data.data.remaining_hp == 0) {
                    ele.listdata[i].is_alive = 0
                }
            }
        }
        // console.log(ele.listdata);
        drawinfo2(ele.listdata);
		// console.log(ele.listdata);
    }


    // 重新渲染攻击后的数据
    function drawinfo2(data) {
        let attackerhtml = ''
        let myuserid = getCookie('userid')
        // 下方列表的数据
        let html = data.map((item, index) => {
            let prowidth = item.remaining_hp / item.hp * 100 + '%';
            let is_alive = item.is_alive == 1 ? '' : 'fliter'
            let aliveimg = item.is_alive == 1 ? '' : '<img class="outimg" src="http://img.qxgs.cc/tiantianlaishouzu/img/arena/taotai.png" alt="">'
            let is_attacked = item.is_attacked == 1 ? 'is_attacked' : ''
            let headerimg = ''
            if(item.head_pic == '' || item.head_pic == null) {
                if(item.sex == 1) {
                    headerimg = 'http://img.qxgs.cc/tiantianlaishouzu/img/my/tx1.png'
                }else {
                    headerimg = 'http://img.qxgs.cc/tiantianlaishouzu/img/my/tx2.png'
                }
            }else {
                headerimg = IMG_DOMAIN + item.head_pic
            }
            let name = item.user_id == myuserid?'我':item.nick_name
            return `<div class="listcontent ${is_attacked}" data="${item.is_alive}" data2="${item.user_id}">
						<div class="list ${is_alive}">
							<div class="progress progress2">
								<img src="http://img.qxgs.cc/tiantianlaishouzu/img/arena/xuedi.png" alt="">
								<div class="">
									<p></p>
									<span style="width:${prowidth}"></span>
								</div>
							</div>
							<div class="headimg3">
								<img class="headimg4" src="http://img.qxgs.cc/tiantianlaishouzu/img/arena/tx2.png" alt="">
								<img class="headimg5" src="${headerimg}" alt="">
								<div class="listin">
									<span class="caizi">${index + 1}</span>
								</div>
							</div>
							<p class="caizi">${name}</p>
							<span class="hhz">豪华值：${item.luxury}</span>
						</div>
						${aliveimg}
					</div>`;
        }).join('');

        ele.peolist.innerHTML = html;
        // 攻击者的数据
        for (let i = 0; i < data.length; i++) {
            if (data[i].is_attacker == 1) {
                attackinfo.user_id = data[i].user_id
                // console.log(attackinfo.user_id);
                attackinfo.is_attacker = data[i].is_attacker
                if(attackinfo.user_id == myuserid) {
                    ele.attackimg.style.display = 'block'
                }else {
                    ele.attackimg.style.display = 'none'
                }
                let d = data[i]
                let prowidth = d.remaining_hp / d.hp * 100 + '%'
                let headerimg2 = ''
                if(data[i].head_pic == '' || data[i].head_pic == null) {
                    if(data[i].sex == 1) {
                        headerimg2 = 'http://img.qxgs.cc/tiantianlaishouzu/img/my/tx1.png'
                    }else {
                        headerimg2 = 'http://img.qxgs.cc/tiantianlaishouzu/img/my/tx2.png'
                    }
                }else {
                    headerimg2 = IMG_DOMAIN + data[i].head_pic
                }
                attackerhtml += `<div class="progress">
                                    <img src="http://img.qxgs.cc/tiantianlaishouzu/img/arena/xuedi.png" alt="">
                                    <p><span style="width:${prowidth}"></span></p>
                                </div>
                                <div class="headimg">
                                    <img class="headimg1" src="http://img.qxgs.cc/tiantianlaishouzu/img/arena/tx.png" alt="">
                                    <img class="headimg2" src="${headerimg2}" alt="">
                                </div>
                                <p class="caizi">${d.nick_name}</p>
                                <span class="hhz">豪华值：${d.luxury}</span>`

                ele.attacker.innerHTML = attackerhtml
                choose();
            }
        }
    }


    // 开始选择攻击的对象
    function choose() {
        let clickitem = $('.list');
        for (let i = 0; i < clickitem.length; i++) {
            clickitem[i].onclick = function () {
                let myuserid = getCookie('userid')
                // console.log(attackinfo.user_id, myuserid);
                if (attackinfo.user_id == myuserid) {
                    let alive = this.getAttribute('data');
                    let user_id = this.getAttribute('data2');
                    if (user_id != myuserid) {
                        // 如果选中的是活的添加类
                        if (alive == 1) {
                            this.classList.add('listactive');
                            // 发送要攻击的对象
                            let data = {
                                type: 'attack',
                                data: {
                                    ring_id: ring_id,
                                    attacked_uid: user_id
                                },
                            }
                            socket.send(JSON.stringify(data))
                            // attack (user_id)
                        } else {
                            openTips('已淘汰');
                        }
                    } else {
                        openTips('不能攻击自己');
                    }
                } else {
                    openTips('您不是攻击者');
                }
            }
        }
    }


    // 禁止选择
    function notchoose() {
        let clickitem = $('.list');
        for (let i = 0; i < clickitem.length; i++) {
            clickitem[i].onclick = ''
        }
    }

    function chooseclear() {
        let clickitem = $('.list');
        for (let i = 0; i < clickitem.length; i++) {
            clickitem[i].classList.remove('listactive')
        }
    }

    // 渲染攻击记录
    function addlog(data) {
        let num = Math.floor(Math.random()*4) + 1
        let color = 'color' + num
        let html = ''
        html += `<p class="${color}">${data.attack_log}</p>`
        ele.attack_log.insertAdjacentHTML('afterbegin', html)
    }

   

})();